import React, { Component } from "react";
import { message, Modal, Button, Input } from "antd";
import { JSEncrypt } from "../../utils/jsencrypt";
import { PUBLI_KEY } from "../../utils/constants";

class PasswordPopup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password: ""
    };
  }

  handleCancel = () => {
    const { onCancel } = this.props;
    onCancel && onCancel();
  };

  handleOk = () => {
    const { onOk } = this.props;
    const { password } = this.state;
    if (/^\d{6}$/.test(password)) {
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(PUBLI_KEY);
      const exPassword = encrypt.encrypt(password);
      onOk && onOk(exPassword);
    } else {
      message.destroy();
      message.warn("请输入6位数字");
    }
  };

  handleChange = e => {
    const password = e.target.value;
    this.setState({ password });
  };

  render() {
    const { title } = this.props;
    const { password } = this.state;
    return (
      <Modal
        title={title}
        visible={true}
        wrapClassName="v-center-modal"
        maskClosable={false}
        width={380}
        footer={null}
        onCancel={this.handleCancel}
      >
        <div className="google-popup">
          <Input
            type={title === "交易密码" ? "password" : "text"}
            size="large"
            autofocus="autofocus"
            value={password}
            placeholder="请输入6位数字"
            onChange={this.handleChange}
          />
          <div className="google-btn">
            <Button type="normal" onClick={this.handleCancel}>
              取消
            </Button>
            <Button onClick={this.handleOk} type="primary">
              确定
            </Button>
          </div>
        </div>
      </Modal>
    );
  }
}

export default PasswordPopup;
